<?php
/**
 * Content - Simple Product Snapshot
 *
 * @version 1.5.0
 * @package Joomla
 * @subpackage plugins
 * 
 * @author Bruno Pourtier
 * @website http://forge.joomla.org/gf/project/simplesnapshot/
 * @email bruno.pourtier@gmail.com
 * @copyright (C) 2008-2011 Bruno Pourtier
 * @license http://www.gnu.org/copyleft/gpl.html GNU/GPL
 *
 * http://www.joomla.org
 *
 * VirtueMart is Free Software.
 * VirtueMart comes with absolute no warranty.
 * http://virtuemart.net
 *
 * Seber Cart is Free Software.
 * Seber Cart comes with absolute no warranty.
 * http://sebercart.com/
 *
 * CLASS FOR VIRTUEMART
 */

class VirtueMartProductSnapshot 
{
	var $_regex = '/{vmproduct:.+?}/';
	var $_name	= 'vmproduct';
	var $_pluginPath;
	var $_pluginUrl;
	var $_pluginParams;
	var $_text;
	
	function onPrepareContent()
	{
		global $sess, $mm_action_url, $CURRENCY_DISPLAY;
		
		/**
		 * MAIN VERIFICATION
		 */
		// Check if there is any {vmproduct} or {simpleproduct} in the text
		if ( !preg_match( $this->_regex, $this->_text )) { return false; }
		
		
		// Check if VirtueMart is installed otherwise this plugin doesn't need to be used
		if (file_exists(JPATH_SITE . DS . 'components' . DS . 'com_virtuemart' . DS . 'virtuemart_parser.php'))
		{
			require_once (JPATH_SITE . DS . 'components' . DS . 'com_virtuemart' . DS . 'virtuemart_parser.php');
			require_once( CLASSPATH . 'ps_product.php');
			require_once( CLASSPATH . 'ps_product_attribute.php');
			require_once( CLASSPATH . 'ps_product_category.php');
			require_once (CLASSPATH . 'ps_reviews.php');
			
			preg_match('#themes/(.+?)/#', VM_THEMEURL, $theme); // Retrieve the VirtueMart theme name
		} 
		else 
		{
			$this->_pluginParams->set('enabled', false);
			if ($this->_pluginParams->get('showerror', 0)) {
				JError::raiseWarning(500, JText::_('SPS_VIRTUEMART_NOTINSTALLED'));
			}
			return false;
		}
		
		/**
		 * FILES INSERTION
		 */
		// Load language translation
		JPlugin::loadLanguage('plg_content_simpleproductsnapshot', JPATH_ADMINISTRATOR);
		// Load VirtueMart Ajax Script & CSS
		$document =& JFactory::getDocument();
		if ($this->_pluginParams->get('ajax', 1)) // Check if AJAX disabled
		{
      $document->addScriptDeclaration('var cart_title = "' . JText::_('SPS_CART') . '"; var ok_lbl="' . JText::_('SPS_CONTINUE') . '"; var cancel_lbl="' . JText::_('SPS_CANCEL') . '"; var notice_lbl="' . JText::_('SPS_NOTICE') . '"; var live_site="'.JUri::root().'";');
      $document->addScript(JURI::root() . 'components/com_virtuemart/fetchscript.php?gzip=0&subdir[0]=/themes/' . $theme[1] . '&file[0]=theme.js&subdir[1]=/js/mootools&file[1]=mooPrompt.js');
		}
		$document->addStyleSheet(JURI::root() . 'components/com_virtuemart/fetchscript.php?gzip=0&subdir[0]=/themes/' . $theme[1] . '&file[0]=theme.css&subdir[1]=/js/mootools&file[1]=mooPrompt.css');
		// END FILES INSERTION
		
		// Check if the plugin is enabled, otherwise replace all regex {simpleproduct} by blank
		if (!$this->_pluginParams->get('enabled')) 
		{
			$this->_text = preg_replace( $this->_regex, '', $this->_text );	
			return true;
		}
		
		/**
		 * PLUGIN PROCESSING
		 */		 
		// Find all instances of plugin and put in $matches
		preg_match_all($this->_regex, $this->_text, $matches);

		// Plugin only processes if there are any instances of the plugin in the text
		if ( count( $matches[0] ) ) 
		{
			// Get plugin parameters
			foreach ($matches[0] as $match) 
			{
				$match = str_replace("{{$this->_name}:", "", $match);
				$match = str_replace("}", "", $match);
				$this->prepareParams($match);

				$ps_product = new ps_product;
				$ps_product_attribute = new ps_product_attribute;
				$ps_product_category = new ps_product_category;
				$db = new ps_DB;
				
				$html = '';
				
				// Define SQL request to retrieve product informations from VirtueMart database
				$product_id = $this->_pluginParams->get('id', 0, '_product');
				$product_sku = $this->_pluginParams->get('sku', 0, '_product');
				if ($product_id) $where = '`product_id` IN (' . $product_id . ')';
				$where = $product_sku ? '`product_sku`IN (\'' . $product_sku . '\')' : $where;
				
				if ($where)
				{
					$q = 'SELECT DISTINCT `product_sku`, `product_name`, `product_id`, `product_parent_id`, `product_thumb_image`, `product_s_desc`, `product_desc`, `product_in_stock`, `product_unit`';
					$q .= ' FROM #__{vm}_product';
					$q .= '	WHERE ' . $where;
					
					$db->query( $q );
				}
				
				if( $db->num_rows() > 0 ) 
				{				
					$tpl = vmTemplate::getInstance();
					$product_id = $db->f('product_id');
					$product_parent_id = $db->f('product_parent_id');
					$cid = $ps_product_category->get_cid($product_id);
					
					// Define the correct url to see the product details page
					$url = 'index.php?page=shop.product_details';
					if ($cid) $url .= '&category_id=' . $cid;
					$url .= ( $product_parent_id ) ? '&flypage=' . $ps_product->get_flypage($product_parent_id) : '&flypage=' . $ps_product->get_flypage($product_id);
					$url .=  '&product_id=' . $product_id;
					
					// Get the current price without formatting
					$base_price = $ps_product->calcEndUserprice($db->f('product_id'), false);
					
					// Set the product informations
					$tpl->set( 'product_id', 			    $db->f('product_id') );
					$tpl->set( 'product_parent_id', 	$db->f('product_parent_id') );
					$tpl->set( 'product_name', 			  $db->f('product_name') );
					$tpl->set( 'product_s_desc', 		  $db->f('product_s_desc') );
					$tpl->set( 'product_description', $db->f('product_desc') );
					//$tpl->set( 'product_price',			  preg_replace('/\$/', '&#36;', $ps_product->show_price( $db->f("product_id"), true )) ); // Get the current price formatted
					$tpl->set( 'product_price',			  $ps_product->show_price( $db->f("product_id"), true )); // Get the current price formatted
					$tpl->set( 'base_price',			    $base_price['product_price'] );
					$tpl->set( 'product_thumb_image', $db->f("product_thumb_image") );
					$tpl->set( 'product_stock',       $db->f("product_in_stock") );
					$tpl->set( 'product_unit',        $db->f("product_unit") ); // Submitted by Jagular .e
					
					// URLS HANDLING
					$ssl    = ($this->_pluginParams->get('forcessl', $this->_pluginParams->get('forcessl'),  '_product')) ? 1 : 0;
          // Not SEF urls
          $tpl->set( 'product_link_notsef', htmlentities(JURI::root() . $sess->url($url)) );
          $tpl->set( 'mycart_link_notsef',  htmlentities(JURI::root() . 'index.php?option=com_virtuemart&page=shop.cart') );
          // SEF urls
          $tpl->set( 'product_link', JRoute::_($sess->url($url), true, $ssl));			
          $tpl->set( 'mycart_link', JRoute::_($sess->url('index.php?option=com_virtuemart&page=shop.cart'), true, $ssl) );
					
					// Set the parameters for displaying product informations
					$tpl->set( 'ajax',                      $this->_pluginParams->get('ajax', 	        $this->_pluginParams->get('ajax'),		        '_product') );        
					$tpl->set( 'show_product_name', 	      $this->_pluginParams->get('showname', 		  $this->_pluginParams->get('showname'),		    '_product') );
					$tpl->set( 'show_product_price', 	      $this->_pluginParams->get('showprice', 		  $this->_pluginParams->get('showprice'), 	    '_product') );
					$tpl->set( 'show_product_desc', 	      $this->_pluginParams->get('showdesc',       $this->_pluginParams->get('showdesc'),        '_product') );
					$tpl->set( 'show_product_description',  $this->_pluginParams->get('showdescription',$this->_pluginParams->get('showdescription'), '_product') );
					$tpl->set( 'show_product_unit', 	      $this->_pluginParams->get('showunit', 		  $this->_pluginParams->get('showunit'), 		    '_product') );
					$tpl->set( 'show_product_image', 	      $this->_pluginParams->get('showimage', 		  $this->_pluginParams->get('showimage'), 	    '_product') );
					$tpl->set( 'show_product_attribute',    $this->_pluginParams->get('showattribute', 	$this->_pluginParams->get('showattribute'),	  '_product') );
					$tpl->set( 'show_product_quantity',     $this->_pluginParams->get('showquantity', 	$this->_pluginParams->get('showquantity'), 	  '_product') );
					$tpl->set( 'show_product_reviews',	    $this->_pluginParams->get('showreviews', 	  $this->_pluginParams->get('showreviews'), 	  '_product') );
					$tpl->set( 'show_product_rating',	      $this->_pluginParams->get('showrating', 	  $this->_pluginParams->get('showrating'), 	    '_product') );
					$tpl->set( 'show_product_stock',	      $this->_pluginParams->get('showstock', 	    $this->_pluginParams->get('showstock'), 	    '_product') );
					$tpl->set( 'show_link_addtocart', 	    $this->_pluginParams->get('showaddtocart',	$this->_pluginParams->get('showaddtocart'),	  '_product') );
					$tpl->set( 'show_link_mycart', 	        $this->_pluginParams->get('showmycart',     $this->_pluginParams->get('showmycart'), 	    '_product') );
					$tpl->set( 'show_link_readmore', 	      $this->_pluginParams->get('showmore', 	    $this->_pluginParams->get('showmore'), 		    '_product') );
					
					// Set the correct template for rendering the product
					if($this->_pluginParams->get('template', $this->_pluginParams->get('template'), '_product')) 
					{
            $tpl->set( 'price',			      $ps_product->show_price( $db->f("product_id"), true ) ); // Get the current price formatted
            $tpl->set( 'addtocart_link', 	$this->_pluginParams->get('showaddtocart',	$this->_pluginParams->get('showaddtocart'),	'_product') );
						$html .=  $tpl->fetch( "common/productsnapshot.tpl.php" );
					}
					elseif($file = $this->_pluginParams->get('file', $this->_pluginParams->get('file'), '_product')) 
					{
						// Load template file
						$tpl->path = $this->_pluginPath . 'templates' . DS . 'virtuemart' . DS;
						
						if (file_exists($tpl->path . DS . $file . '.css'))
						{
							$document->addStyleSheet($this->_pluginUrl . 'templates/virtuemart/' . $file . '.css');
						}
						else
						{
							if ($this->_pluginParams->get('showerror', 0)) {
								JError::raiseWarning(500, sprintf(JText::_('SPS_TEMPLATE_NOFILE'), $file . '.css'));
							}
						}
						
						if (file_exists($tpl->path . $file . '.tpl.php' ))
						{
							$html .= $tpl->fetch( $file . '.tpl.php' );
						} 
						else 
						{
							if ($this->_pluginParams->get('showerror', 0)) {
								JError::raiseWarning(500, sprintf(JText::_('SPS_TEMPLATE_NOFILE'), $file . '.tpl.php'));
							}
						}
					}
					else 
					{
						if ($this->_pluginParams->get('showerror', 0)) {
							JError::raiseWarning(500, JText::_('SPS_TEMPLATE_EMPTY'));
						}
					}
				} 
				else 
				{
					if ($this->_pluginParams->get('showerror', 0)) {
						JError::raiseWarning(500, sprintf(JText::_('SPS_PRODUCT_UNAVAILABLE'), ($product_sku ? $product_sku : $product_id)));
					}
				}

				$html = preg_replace('/\$/', '&#36;', $html);
				$this->_text = preg_replace( $this->_regex, $html, $this->_text, 1 );
			}
		}
	}
	
	function prepareParams($match)
	{
		$this->_pluginParams->bind(array(
			'id' 			        => '',
			'sku' 			      => '',
			'enabled'		      => $this->_pluginParams->get('enabled', 		    1),
      'forcessl' 		    => $this->_pluginParams->get('forcessl', 		    0),
			'template' 		    => $this->_pluginParams->get('template', 		    0),
			'file'			      => $this->_pluginParams->get('file', 			      'default'),
			'ajax'			      => $this->_pluginParams->get('ajax', 			      1),
			'showname'		    => $this->_pluginParams->get('showname', 		    1),
			'showdesc'		    => $this->_pluginParams->get('showdesc', 		    1),
			'showdescription' => $this->_pluginParams->get('showdescription', 0),
			'showunit'		    => $this->_pluginParams->get('showunit', 		    1),
			'showimage'		    => $this->_pluginParams->get('showimage', 		  1),
			'showprice'		    => $this->_pluginParams->get('showprice', 		  1),
			'showattribute'	  => $this->_pluginParams->get('showattribute',   1),
			'showquantity'	  => $this->_pluginParams->get('showquantity', 	  1),
			'showaddtocart'	  => $this->_pluginParams->get('showaddtocart',   1),
			'showreviews'	    => $this->_pluginParams->get('showreviews', 	  1),
			'showrating'	    => $this->_pluginParams->get('showrating', 	    1),
			'showmore'		    => $this->_pluginParams->get('showmore', 		    1),
			'showmycart'	    => $this->_pluginParams->get('showmycart', 	    1)
		), '_product');
		
		$params = explode( ",", $match );
		foreach( $params as $param ) 
		{
			$param = explode( "=", $param );
			$this->_pluginParams->set($param[0], $param[1], '_product');
		}
	}
	
	/**
   * INTEGRATION CHILDREN PRODUCTS
   * DON'T DELETE FOLLOWING LINES
   */
	public function displayAttributes($product_id) 
	{
    global $VM_LANG;
    $ps_product = new ps_product();

    $db = new ps_DB();
    $db_sku = new ps_DB();
    $db_item = new ps_DB();
    $db_price = new ps_DB();
    $itemid = ps_session::getShopItemid();

    $q = "SELECT product_id,product_name FROM #__{vm}_product ";
    $q .= "WHERE product_parent_id='" . $product_id . "' AND product_publish='Y'" ;
    $db->setQuery( $q );
    $db->query();

    $product_parent_id = $product_id;

    if( $db->num_rows() < 1 )
    {
      $product_parent_id = $ps_product->get_field( $product_id, 'product_parent_id' ) ;
      if( $product_parent_id != 0 ) 
      {
        $product_id = $product_parent_id;
        $q = "SELECT product_id,product_name FROM #__{vm}_product ";
        $q .= "WHERE product_parent_id='{$product_id}' AND product_parent_id<>0 AND product_publish='Y'" ;
        $db->setQuery( $q.$q1 ) ;
        $db->query() ;
      }
    }

    if( $db->num_rows() > 0 )
    {
      $child_html = "<label for=\"product_id_field\">" . $VM_LANG->_( 'PHPSHOP_PLEASE_SEL_ITEM' ) . "</label>:<br />\n";
      $child_html .= "<select class=\"inputbox\" id=\"product_id_field\" name=\"prod_id[]\">\n";
      $child_html .= "<option value=\"$product_id\">" . $VM_LANG->_( 'PHPSHOP_SELECT' ) . "</option>";
      while ( $db->next_record()) 
      {	
        $product_parent_id = $product_id;        
        $child_id = $db->f('product_id');
        
        $child_html .= '<option value="' . $child_id . '">';
        $child_html .= $db->f('product_name') . ' - ';

        $q = 'SELECT product_id, attribute_name ';
        $q .= 'FROM #__{vm}_product_attribute_sku ';
        $q .= "WHERE product_id='" . $product_id . "' ORDER BY attribute_list ASC";
        $db_sku->setQuery( $q ) ;
        $db_sku->query() ;
        
        $i=0;
        while ( $db_sku->next_record()) 
        {
          $q = 'SELECT attribute_name, attribute_value, product_id ';
          $q .= 'FROM #__{vm}_product_attribute ';
          $q .= "WHERE product_id='" . $child_id . "' AND attribute_name='" . $db_sku->f('attribute_name') . "'";
          $db_item->setQuery( $q );
          $db_item->query();
          
          while ($db_item->next_record())
          {
            $i++;
            $child_html .= $db_item->f('attribute_name') . ' ';
            $child_html .= '(' . $db_item->f('attribute_value') . ')';
            if ($i < $db_sku->num_rows()) $child_html .= '; ' ;
          }
        }
        $child_html .= ' - ' . $ps_product->show_price( $child_id, true );
        $child_html .= '</option>';
      }
      $child_html .= '</select>';
    }
    else 
    {
      $child_html = '<input type="hidden" name="prod_id[]" value="' . $product_id . '" />';
    }
    
    return $child_html;
	}
}
?>